<?php
namespace app\task\controller;

class Order extends Base
{
    private $tn = 'order';

    public function index()
    {
        if (isset($this->get['page']) && isset($this->get['limit'])) {
            $where = [];
            if(isset($this->get['task_id'])){
                $where['task_id'] = $this->get['task_id'];
            }
            if(isset($this->get['keywords'])){
                $where['title|nick_name'] = ['like','%'.$this->get['keywords'].'%'];
            }
            if(isset($this->get['date'])){
                $where['o.add_time'] = ['between',[strtotime($this->get['date']),strtotime($this->get['date']."+1 day")]];
            }
            if(isset($this->get['status'])){
                $where['o.status'] = $this->get['status'];
            }
            $list  = db($this->tn)->alias('o')->join('task t','t.id = o.task_id')->join('user u','u.id = o.user_id')->field('nick_name,account,title,o.id,account,FROM_UNIXTIME(o.add_time,"%Y-%m-%d %H:%i") as add_time,o.status,task_id,t.type,o.price,t.validate_time as task_time,t.status as task_status')->where($where)->order(['id' => 'desc'])->page($this->get['page'])->limit($this->get['limit'])->select();
            foreach($list as $key=>$val){
                //如果该任务没有完成并且有效时间已过并且该接单没有完成则视为过期
                if($val['task_time'] < time() && in_array($val['task_status'],[2,3])&&$val['status'] == 2){
                    $list[$key]['status'] = 5;
                }
            }

            $count = db($this->tn)->alias('o')->join('task t','t.id = o.task_id')->join('user u','u.id = o.user_id')->where($where)->count();
            $this->returnAPI('', 0, $list, ['count' => $count]);
        }
        return $this->fetch();
    }

    public function edit($id = 0)
    {
        $model = model($this->tn);
        if ($this->post) {
            $id = $this->post['id'];
            unset($this->post['id']);
            $model = $model->get($id);
            if (is_null($model)) {
                $this->returnAPI('信息有误，请稍后重试');
            }
            $task_info = model('task')->get($model['task_id']);
            if(is_null($task_info)){
                $this->returnAPI('该任务不存在');
            }
            
            db()->startTrans();
            if($this->post['status'] == 3){
    
                $this->post['finish_time'] = time();

                $user_id = $model['user_id'];
                $user = db('user');
                $config = db('config');
                $log = db('handle_log');
                
                $user_info =  $user->where('id',$user_id)->find();
                switch($user_info['grade']){
                    case 0: $finish_price = $config->where('key','p_finish')->find()['value'];break;
                    case 1: $finish_price = $config->where('key','y_finish')->find()['value'];break;
                    case 2: $finish_price = $config->where('key','e_finish')->find()['value'];break;
                    case 3: $finish_price = $config->where('key','s_finish')->find()['value'];break;
                }
               
               
                if($finish_price > 0){
                    $this->post['price'] = $finish_price;
                    if(!$user->where('id',$user_id)->setInc('balance',$finish_price)){
                        db()->rollback();
                        $this->returnAPI('修改用户余额失败');
                    }
                    //添加记录
                    if(!$log->insert(['user_id'=>$user_id,'content'=>'完成任务-'.$task_info['title'],'handle_num'=>$finish_price,'handle_type'=>1,'classify'=>5,'add_time'=>time(),'foreign_key'=>$model['task_id']])){
                         db()->rollback();
                        $this->returnAPI('添加记录失败');
                    }
                }
                
                
                
                //修改任务状态
                $finish_count = db('order')->where(['task_id'=>$model['task_id'],'status'=>3])->count();
                if($finish_count +1 >= $task_info['number']){
                    if(!$task_info->save(['status'=>4,'finish_time'=>time()])){
                        db()->rollback();
                        $this->returnAPI('修改任务状态失败');
                    }
                }
                $con = '审核通过';
            }else{
                $con = '审核驳回';
            }
            //消息
            if(!db('information')->insert(['user_id'=>$model['user_id'],'type'=>1,'title'=>$task_info['title'],'content'=>$con,'add_time'=>time()])){
                db()->rollback();
                $this->returnAPI('添加消息失败');
            }
            $result = $model->validate($this->tn)->allowField(true)->save($this->post);
            if ($result === false) {
                db()->rollback();
                 $this->returnAPI($model->getError());
                
            }
            db()->commit();
             $this->returnAPI('操作成功', 0);
        }
        $model = $model->alias('o')->join('task t','t.id = o.task_id')->where('o.id',$id)->field('o.*,title,t.type,t.remark,t.thumb_image,t.validate_time as task_time,t.status as task_status')->find();
        if (is_null($model)) {
            $data = $this->table_fields($this->tn);
        } else {
            $data = $model->getData();
            if($data['thumb_image']){
                $data['image'] = explode(',',$data['thumb_image']);
            }else{
                $data['image'] = [];
            }
            if($data['submit_image']){
                $data['submit_image'] = explode(',',$data['submit_image']);

            }else{
                 $data['submit_image']  = [];
            }
            if($data['task_time'] < time() && in_array($data['task_status'],[2,3])&&$data['status'] == 2){
                $data['status'] = 5;
            }
            
        }
       
        return $this->fetch('', [
            'data' => $data,
        ]);
    }
}
